package cn.clouds234.jschdemo;

import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * 测试jschUtils功能
 * @author wyf
 * @description 描述类的功能
 * @date 2024/4/30 14:09
 */
public class JschClient {

    public static void main(String[] args) throws JSchException, SftpException, IOException, InterruptedException {
//        uploadFileAndInstall();
//        listFile();
//        shellDemo();
        testPvkConnect();
//        testPwConnect();
    }
    public static void testPwConnect() throws JSchException, SftpException {
        JSchUtils jSchUtils = new JSchUtils();
        jSchUtils.connectByPassword("root", "wyf@564335", "192.168.56.101", 22);
        Vector vector = jSchUtils.listFiles("/home");
        for (Object o : vector) {
            System.out.println(o);
        }

    }

    public static void testPvkConnect() throws JSchException, SftpException {
        String pvk = "-----BEGIN OPENSSH PRIVATE KEY-----\n" +
                "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn\n" +
                "NhAAAAAwEAAQAAAYEAwLW/wUYwkhlJJtjHQdREQIIhE/fOtF4EF0qxTZczuPTpKngfwsib\n" +
                "HcNRBB5h2c7FuMJkH126ZZj+lywUFlvEVCDzf0xsZuEu1oF4M2ryzzf7dsiideo4R7eSWv\n" +
                "bFytg51nocezpUiy1eal1z7VF7fpy28nEoRjvk15PBxE1kGOkpCyt/99wF76y5krdclHsz\n" +
                "38Q2TFvctcYK3Nr/ziGTq6ojgJeHgDggS1URWgstrbr+Nx1SZo8au0GUodq+ka1ERXj1ys\n" +
                "bJXBuL9Kdcp/FXQdRQ1ZH8RF0kgfz9BlzTvZhJPDSVAhUjEHQ7dvl0zoyIj32rI8YUtmou\n" +
                "0VoF/cHIPfFQmcIBX8fUtKy39IIHPb6AXfB5b5xs6KcVxCKaJSgjQqJ3w46ELgiK6X1YDX\n" +
                "5ehkLVyGcwcajhiEr2KI54MC2wbC3RHmS7H4acYGQhRk7ybCtzmtP+N0sqL4dLjGsHPKEM\n" +
                "DfTl84dhzpg3BWwYZ5yQWITS71STS0LAMw9RvDadAAAFiB2Y+RUdmPkVAAAAB3NzaC1yc2\n" +
                "EAAAGBAMC1v8FGMJIZSSbYx0HURECCIRP3zrReBBdKsU2XM7j06Sp4H8LImx3DUQQeYdnO\n" +
                "xbjCZB9dumWY/pcsFBZbxFQg839MbGbhLtaBeDNq8s83+3bIonXqOEe3klr2xcrYOdZ6HH\n" +
                "s6VIstXmpdc+1Re36ctvJxKEY75NeTwcRNZBjpKQsrf/fcBe+suZK3XJR7M9/ENkxb3LXG\n" +
                "Ctza/84hk6uqI4CXh4A4IEtVEVoLLa26/jcdUmaPGrtBlKHavpGtREV49crGyVwbi/SnXK\n" +
                "fxV0HUUNWR/ERdJIH8/QZc072YSTw0lQIVIxB0O3b5dM6MiI99qyPGFLZqLtFaBf3ByD3x\n" +
                "UJnCAV/H1LSst/SCBz2+gF3weW+cbOinFcQimiUoI0Kid8OOhC4Iiul9WA1+XoZC1chnMH\n" +
                "Go4YhK9iiOeDAtsGwt0R5kux+GnGBkIUZO8mwrc5rT/jdLKi+HS4xrBzyhDA305fOHYc6Y\n" +
                "NwVsGGeckFiE0u9Uk0tCwDMPUbw2nQAAAAMBAAEAAAGAAqrxcOBDH16kvdot5foliLwUb6\n" +
                "WUUbhkd5sT2cZgU6zmRm17yRNEXHTd+//crGp5n71nK+z8/deQnLCiRY33KY/8NvSson73\n" +
                "CkaoDpQqMNauTz5nS1kW9t0ydDpq0gxMvqyZlNYhofyajD/ncS9Z1Y6fVLteypwdJqPXwJ\n" +
                "suqc6egBZV0u1TkrYSKpcJu8950Bz0AHocE9MeRuDsPiMGW4/DJo5SdKKyRcCzeQrjEr7e\n" +
                "Mo6gG6XbAaEeiOARl8wtednO1Sc7rJUTEiAg3BWqwGq2FKcTzGuhdxFDC0CvZmK6ozd87Y\n" +
                "LEU9dovQVf6Ft1FqYmfaf1sLNf72al/e1WkJBMNaPbRGkwS3MEF+m88yk4CZBmSKWrBhCk\n" +
                "Q9WpHSY+sBRIcFal1xmwoVfCj+P0rv5STQNFGhGIKRQcPe0u4QmQCTHlJA3BVU0W9vNF6h\n" +
                "trDGqxmSUylrVJk/nlogNfW67d1Zt+GCRuuaEyemEl/yzS8TNx5sIWOEndhW5sHEpRAAAA\n" +
                "wEju/GtULU8QC5Celu3j45LwMUMW5SGbXUmov8gkug25zBkL5JuZsxjVsySOelE6a5yCFF\n" +
                "LCVd2eia4FcUVNmz1zDt3zWa7euxtM93JX2iUCxjHEs8lvmKYhCix+b0BjM7jD3wU7nECc\n" +
                "436PVzkp+yZrjg3aancLWyNJy1S4RzlGuokaV+wpndi7O5MJHUikfArnjhAhM2VO+GhrYJ\n" +
                "XiBZoho/wEKL+tpp8hw4xe/6LHJB9JPyofXkPRBDirgII9XgAAAMEA8a8i6Zco9+qYe6od\n" +
                "uzySFLcbLddOGhcQoQucUglCxEA1xCBgIlMM+mZi4Zc7foLHMqu6Hr+SkandpVO10Me+Ha\n" +
                "wilEPU5Xm4KDZu+NLGfciLQp9AalGOYIHC1D9I+zdoWHTqIvICP0xUPf1LF4m47zzmK2f5\n" +
                "ulo/wGr3/Mfnl7yIGfITcBRM69TCzNAPg7jSwmTxFXdzXI9ZmD7b4gjFXHMKdKINkLfCf4\n" +
                "2ivSCKfGv8boosgpzL0S8A7jfZ0zyxAAAAwQDMH/mwbCFlUf4Rclnh59GjftdyxwoDNoUd\n" +
                "VYRlHNo/f26yPck522Lgcf6OKAvRT4majFjFsR/VBPzLo7l5kExSrTlTbJBum4JxtYzLex\n" +
                "cEVvfrS59LbPa7mG1ltyv4h5jASKL3tROao72b8PIuvNOZI1cBXAQKlJ3MmHFJWrBrK4LT\n" +
                "WKOqQIUKuyg4cMP8MlUKR714OkNZvuiSWhyXaAHyvVgpj+DiNC7qnDhF3Gnrzf8PwFpSer\n" +
                "H/GM8yzHOwI60AAAAQcm9vdEBjY2wtdm0tMTU4NgECAw==\n" +
                "-----END OPENSSH PRIVATE KEY-----";
        JSchUtils jSchUtils = new JSchUtils();
//        jSchUtils.connectByPvk("root", pvk.getBytes(StandardCharsets.UTF_8), "10.64.15.86", 22);
        jSchUtils.connectByPvk("root", "F:/data/101rsa.txt", "10.64.7.202", 22);
        Vector vector = jSchUtils.listFiles("/home");
        for (Object o : vector) {
            System.out.println(o);
        }
    }

    /**
     * 模拟shell交互多条命令。直到命令执行失败结束。
     * XXX 命令执行结果输入流阻塞执行导致程序无法执行下去。
     * @author wyf
     * @date 2024/12/10 21:12
     */
    public static void shellDemo() throws JSchException, IOException {
        String[] cmds = new String[]{"ls /home","ls -l"};
        JSchUtils jSchUtils = new JSchUtils();
        jSchUtils.connectByPassword("root", "Gientech2022!", "10.64.15.86", 22);
        Session session = jSchUtils.getSession();
        ChannelShell shell = (ChannelShell) session.openChannel("shell");
        //获取输入
        InputStreamReader inputStreamReader = new InputStreamReader(shell.getInputStream());
        // 用于接收返回信息
        BufferedReader in = new BufferedReader(inputStreamReader);

        //输出
        PrintWriter printWriter = new PrintWriter(shell.getOutputStream());
        // 启动shell通道
        shell.setPty(true);
        shell.connect();
        // 读取命令执行结果
        String line;
        for (String cmd : cmds) {
            while (!(line = in.readLine()).isEmpty()) {
                System.out.println(line);
            }
            System.out.println("执行命令=" + cmd);
            printWriter.println(cmd);
            printWriter.flush();
            while ((line = in.readLine()) !=null) {
                System.out.println(line);
            }
            printWriter.println("echo $?");
            printWriter.flush();
            line = in.readLine();
            if (!"0".equals(line.trim())){
                System.out.println("命令执行失败。" + line);
            }
        }

        System.out.println("命令执行完毕。");
        shell.disconnect();
        session.disconnect();
    }

    public static void listFile() throws JSchException, SftpException {
        JSchUtils jSchUtils = new JSchUtils();
        jSchUtils.connectByPassword("root", "Gientech2022!", "fe80::c4aa:c0ff:fe27:24c1", 22);

        String workDir = "/home/";
        Vector vector = jSchUtils.listFiles(workDir);
        vector.forEach(System.out::println);
    }

    public static void uploadFileAndInstall() throws JSchException, SftpException, IOException, InterruptedException {
        /*
        连接服务器
        创建目录
        上传文件
        解压文件
        启动程序
         */
        JSchUtils jSchUtils = new JSchUtils();
        jSchUtils.connectByPassword("root", "Gientech2022!", "10.64.15.134", 22);

        String workDir = "/home/";
        String appDir = "app/";
        String bakDir = "bak/";

//        jSchUtils.mkdir(workDir);
//
//        jSchUtils.upload(workDir, "F:\\data\\jachTest\\webapps.zip");

        String fileName = "webapps.zip";
        // 安装配置命令
        List<String> cmds = new ArrayList<>();
        // -q静默方式。-o覆盖已存在文件
        String unzip = "unzip -oq " + fileName + " -d ./" + appDir;
//        String chmod = "chmod +x -R " + appDir + "/bin";
        cmds.add(unzip);
//        cmds.add(chmod);

        String s = jSchUtils.execCmd(workDir, ";", cmds);
        System.out.println(s);
        jSchUtils.closeSession();

    }
}
